// pages/fly/fly.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: 'https://moumou-1301304205.cos.ap-shenzhen-fsi.myqcloud.com/nine-thirth/system-img/',
    showNumGame: true, //展示纯数字游戏
    piece: [],
    history: [],
    pieceRule: [{
        'execute': 0,
        'name': '待执行'
      },
      {
        'execute': 1,
        'name': '已执行',
        'color': '#bbe8ff'
      },
      {
        'execute': 2,
        'name': '欠着',
        'color': '#ffdeeb'
      },
      {
        'execute': 3,
        'name': '再掷一次',
        'color': '#ccc'
      },
    ],
    show: false, //popur是否展示
    currentIndex: 0, //当前的数据
  },

  // 获取历史记录
  getHistory(e) {
    let history = wx.getStorageSync('history')
    this.setData({
      history:history
    })
    // wx.cloud.callFunction({
    //   name: 'nine_thirth',
    //   config: {
    //     env: this.data.envId
    //   },
    //   data: {
    //     club_function: "Get_School_Club_List",
    //     schoolID: e,
    //     approval_status: 1,
    //   }
    // }).then((resp) => {
    //   console.log("社团列表信息：", resp)
    //   this.setData({
    //     result: resp.result.data
    //   })
    // }).catch((e) => {
    //   console.error('获取活动数据失败:', e);
    // });
  },

  // 展示纯数字游戏
  numGame(e) {
    // console.log(e);
    let num = e.currentTarget.dataset.num
    let showNumGame = num == 'true' ? true : false
    if(!showNumGame){
      this.getHistory()
    }
    this.setData({
      showNumGame: showNumGame
    })
  },

  switchPiece() {
    let piece = this.data.piece
    let pieceIndex = piece.length - 1
    if (piece.length != 0 && piece[pieceIndex].execute == 0) {
      wx.showToast({
        title: '请去执行上一步',
        icon: 'none'
      })
      return
    }
    // 生成一个0到1之间的随机数
    let randomValue = Math.random();
    // 将这个随机数映射到1到6的范围
    let result = Math.floor(randomValue * 6) + 1;
    // console.log(result);
    let img = `piece${result}.png`
    let obj = {
      'execute': 0,
      'name': '待执行',
      'pieceNum': result,
      'img': img
    }
    piece.push(obj)
    this.setData({
      piece: piece,
      show: true,
      currentIndex: piece.length - 1
    })
    wx.setStorageSync('piece', piece)
    if (piece.length == 1) {
      wx.setStorageSync('pieceStartTime', new Date())
    }
  },

  showPiece(e) {
    let that = this
    // console.log(e);
    let index = e.currentTarget.dataset.index
    let execute = e.currentTarget.dataset.execute
    if (execute != 1) {
      this.setData({
        currentIndex: index,
        show: true
      })
    } else {
      wx.showModal({
        title: '想重新来?',
        content: '后果自负噢',
        complete: (res) => {
          if (res.cancel) {
            wx.showToast({
              title: '好吧',
              icon: 'none'
            })
          }
          if (res.confirm) {
            wx.showToast({
              title: '加油',
              icon: 'none'
            }, 1000)
            that.setData({
              piece: [],
              currentIndex: index,
            }, () => {
              wx.showToast({
                title: '没后悔吧',
                icon: 'none'
              })
            })

          }
        }
      })
    }

  },

  // 执行按钮
  execute(e) {
    let that = this
    console.log(e);
    let executeIndex = e.currentTarget.dataset.execute
    let piece = this.data.piece
    let pieceRule = this.data.pieceRule
    let currentIndex = this.data.currentIndex
    if (executeIndex != 3) {
      piece[currentIndex].execute = pieceRule[executeIndex].execute
      piece[currentIndex].name = pieceRule[executeIndex].name
      wx.setStorageSync('piece', piece)
      this.setData({
        piece: piece,
        show: false
      }, () => {
        if (that.data.piece.length >= 20) {
          wx.showModal({
            title: '完成！',
            content: '恭喜你完成了20次挑战，下次见~欠着的记得还！',
            complete: (res) => {
              if (res.cancel) {
                that.clearPiece()
              }
              if (res.confirm) {
                that.clearPiece()
              }
            }
          })
          return
        }
      })
    } else {
      piece.pop()
      wx.setStorageSync('piece', piece)

      this.setData({
        piece: piece,
        currentIndex: piece.length - 1,
        show: false
      }, () => {
        setTimeout(function () {
          that.switchPiece();
        }, 1000);
      })
    }
  },



  onClose() {
    this.setData({
      show: false
    });
  },

  // 结束游戏
  gameOver() {
    let that = this
    wx.showModal({
      title: '确定结束游戏？',
      content: '结束游戏后，游戏记录可以在历史记录中查找',
      complete: (res) => {
        if (res.cancel) {
          wx.showToast({
            title: '加油',
            icon: 'none'
          })
        }

        if (res.confirm) {
          that.clearPiece()
        }
      }
    })
  },

  clearPiece() {
    let piece = wx.getStorageSync('piece')
    let history = wx.getStorageSync('history') || []
    let obj = {
      'startTime': wx.getStorageSync('pieceStartTime'),
      'histroyItem': piece,
      'overTime': new Date()
    }
    history.push(obj)
    this.setData({
      piece: []
    })
    wx.setStorageSync('history', history)
    wx.setStorageSync('piece', [])
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let piece = wx.getStorageSync('piece') || []
    this.setData({
      piece: piece
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})